package com.ruoyi.project.module.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.project.module.errorcodeCache.domain.ErrorcodeCache;
import com.ruoyi.project.module.errorcodeCache.mapper.ErrorcodeCacheMapper;
import org.shoukaiseki.apiview.common.util.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * com.ruoyi.project.module.task.ErrorCodeJson
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  18-12-14 上午11:49<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Component
public class ErrorCodeJson {

    @Resource
    private ErrorcodeCacheMapper errorcodeCacheMapper;

    @Resource
    ErrorCodeCacheTask errorCodeCacheTask;

    public byte[] exportJson(){
        errorCodeCacheTask.updateErrorCodeCacheNoParams();

        HashMap<Object, Object> map = Maps.newLinkedHashMap();
        List<ErrorcodeCache> list = errorcodeCacheMapper.groupByErrorGroup();
        for (ErrorcodeCache errorcodeCache:list ) {
            Integer errorgroup = errorcodeCache.getErrorgroup();
            List<ErrorcodeCache> errorcodeCacheList = errorcodeCacheMapper.selectByErrorGroup(errorgroup);
            ArrayList<Object> errorcodeList = Lists.newArrayList();
            for (ErrorcodeCache errorcodeTemp : errorcodeCacheList) {
                Integer errorcode = errorcodeTemp.getErrorcode();
                if(errorcode==null){
                    errorcode=0;
                }
                String description = errorcodeTemp.getDescription();
                if(description==null){
                    description="服务器处理错误";
                }
                errorcodeList.add(ImmutableMap.of("errorcode", errorcode,"description",description));
            }
            map.put(String.valueOf(errorgroup),errorcodeList);
        }

        String s = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.PrettyFormat);

        byte[] data = s.getBytes(StandardCharsets.UTF_8);
        return data;
    }
}
